from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from django.conf import settings


def create_bucket(bucket, region='ap-chengdu'):
    # secret_id = 'AKIDgBPRCfrmQovlKcVEhz4uUpthFYbNt99t'  # 替换为用户的 secretId
    # secret_key = 'Xoqc8NN7aomVx94kALFtHPIvHNDsHQJv'  # 替换为用户的 secretKey
    # region = 'ap-chengdu'  # 替换为用户的 Region

    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)

    client = CosS3Client(config)

    response = client.create_bucket(
        Bucket=bucket,
        ACL="public-read-write"  # private  /  public-read / public-read-write
    )
    # 跨域问题设置一下
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': "*",
                'ExposeHeader': "*",
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(
        Bucket=bucket,
        CORSConfiguration=cors_config
    )


# 上传文件
# response = client.upload_file(
#     Bucket='tangzhiming-1309510181',
#     LocalFilePath='code.png',  # 本地文件的路径
#     Key='p1.jpg',  # 上传到桶之后的文件名
# )
# print(response['ETag'])

def uploadfile(bucket, region, file_object, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)

    client = CosS3Client(config)
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_object,  # 文件对象
        Key=key  # 上传到桶之后的文件名
    )
    # 上传之后返回我的图片路径
    # https://tangzhiming-1309510181.cos.ap-chengdu.myqcloud.com/p1.jpg 文件名称的构成
    return "https://{}.cos.{}.myqcloud.com/{}".format(bucket, region, key)


def deletefile(bucket, region, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)

    client = CosS3Client(config)

    client.delete_object(
        Bucket=bucket,
        Key=key  # 上传到桶之后的文件名
    )
    # 上传之后返回我的图片路径
    # https://tangzhiming-1309510181.cos.ap-chengdu.myqcloud.com/p1.jpg 文件名称的构成
    # return "https://{}.cos.{}.myqcloud.com/{}".format(bucket,region,key)


def deletefile_list(bucket, region, key_list):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)

    client = CosS3Client(config)
    objects = {
        "Quiet": "true",
        "Object": key_list
    }

    client.delete_objects(
        Bucket=bucket,
        Delete=objects  # 上传到桶之后的文件名
    )


def credential(bucket, region):
    """获取cos临时凭证"""
    # 生成一个临时凭证，并给前端返回
    # 1. 安装一个生成临时凭证python模块   pip install -U qcloud-python-sts
    # 2. 写代码
    from sts.sts import Sts
    config = {
        # 临时密钥有效时长，单位是秒（30分钟=1800秒）
        'duration_seconds': 1800,
        # 固定密钥 id
        'secret_id': settings.TENCENT_COS_ID,
        # 固定密钥 key
        'secret_key': settings.TENCENT_COS_KEY,
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': '*',
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 'name/cos:PutObject'
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # "name/cos:UploadPart",
            # "name/cos:UploadPartCopy",
            # "name/cos:CompleteMultipartUpload",
            # "name/cos:AbortMultipartUpload",
            "*",
        ],

    }
    sts = Sts(config)
    result_dict = sts.get_credential()
    # 返回的是字典
    return result_dict


def check_file(bucket, region, key):
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)

    client = CosS3Client(config)

    result = client.head_object(
        Bucket=bucket,
        Key=key  # 上传到桶之后的文件名
    )
    # print(result)
    return result


def delete_bucket(bucket, region):
    """删除桶"""
    # 删除所有文件
    # 删除所有碎片
    # 删除桶
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    # 找到桶的所有文件 并且删除
    while True:
        part_objects = client.list_objects(bucket)

        contents = part_objects.get('Contents')  # 如果还有值，还没删完了
        if not contents:
            break
        # 批量删除
        objects = {
            "Quiet": "True",
            "Object": [{"Key": item["Key"]} for item in contents]
        }
        client.delete_object(bucket, objects)
        if part_objects['IsTruncated'] == "false":
            break

    # 找碎片 & 删除碎片
    while True:
        part_uploads = client.list_multipart_uploads(bucket)

        uploads = part_uploads.get('Upload')  # 如果还有值，还没删完了
        if not uploads:
            break
        # 批量删除
        for item in uploads:
            client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
        if part_uploads['IsTruncated'] == "false":
            break

        #删除桶
        client.delete_object(bucket)

        # 视频里一个异常，我没写